import 'package:aqua_plunge/constants/colors.dart';
import 'package:aqua_plunge/dao/broadcaster_dao.dart';
import 'package:aqua_plunge/model/Author.dart';
import 'package:aqua_plunge/model/media.dart';
import 'package:aqua_plunge/services/database_service.dart';
import 'package:aqua_plunge/util/toast_util.dart';
import 'package:aqua_plunge/util/view_util.dart';
import 'package:aqua_plunge/widget/custom_avatar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

import '../controller/DatabaseListController.dart';

class VideoPlayItemPage extends StatefulWidget {
  final Media media;
  final VoidCallback onBlock;
  final VideoPlayerController videoPlayerController;
  final int pageIndex;

  const VideoPlayItemPage(
      {super.key,
      required this.media,
      required this.onBlock,
      required this.videoPlayerController,
      required this.pageIndex});

  @override
  State<VideoPlayItemPage> createState() => _VideoPlayItemPageState();
}

class _VideoPlayItemPageState extends State<VideoPlayItemPage> {
  late Future<void> videoPlayFuture;
  bool playing = true;
  final DatabaseService _databaseService = DatabaseService.instance;
  final DatabaseController _databaseController = Get.find<DatabaseController>();
  Author? author;
  bool loading = true;

  get _appBarView => Obx(() {
        author = _databaseController.authors[widget.media.userId.toString()];
        return Container(
          padding: const EdgeInsets.only(left: 24, right: 24),
          child: Stack(
            children: [
              Row(
                children: [
                  CustomAvatar(
                      width: 42, height: 42, netPath: author?.avatar ?? ''),
                  const SizedBox(width: 12),
                  Flexible(
                      child: Text(
                    author?.nickname ?? "",
                    maxLines: 1,
                    overflow: TextOverflow.clip,
                    style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.white),
                  )),
                  const SizedBox(width: 8),
                  GestureDetector(
                      onTap: () {
                        setState(() {
                          loading = true;
                        });
                        author!.isFriend!
                            ? BroadCasterDao.unFriend(
                                int.parse(author!.userId!), () {
                                appToast.showTipLong('Unfollow Successfully');
                                _databaseService.updateAuthorFriend(
                                    int.parse(author!.userId!), false);
                                _databaseController
                                    .authors[widget.media.userId.toString()]
                                    ?.isFriend = false;
                                setState(() {
                                  loading = false;
                                });
                              })
                            : BroadCasterDao.addFriend(
                                int.parse(author!.userId!), () {
                                appToast.showTipLong('Follow Successfully');
                                _databaseService.updateAuthorFriend(
                                    int.parse(author!.userId!), true);
                                _databaseController
                                    .authors[widget.media.userId.toString()]
                                    ?.isFriend = true;
                                setState(() {
                                  loading = false;
                                });
                              });
                      },
                      child: Image.asset(
                        author?.isFriend ?? false
                            ? 'images/icon_followed.png'
                            : 'images/icon_unfollow.png',
                        width: 38,
                        height: 26,
                      )),
                  const SizedBox(width: 48),
                ],
              ),
              Positioned(
                right: 0,
                child: GestureDetector(
                  onTap: () {
                    _showBottomSheet();
                  },
                  child: Image.asset(
                    "images/icon_more.png",
                    width: 24,
                    height: 42,
                  ),
                ),
              )
            ],
          ),
        );
      });

  _bottomView(context) {
    return SizedBox(
      width: MediaQuery.of(context).size.width,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Container(
              padding: const EdgeInsets.only(left: 24),
              alignment: Alignment.centerLeft,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    widget.media.title ?? "",
                    maxLines: 1,
                    style: const TextStyle(color: Colors.white, fontSize: 16),
                    textAlign: TextAlign.left,
                  ),
                  const SizedBox(
                    height: 12,
                  ),
                  Text(widget.media.describe ?? "",
                      maxLines: 2,
                      style: const TextStyle(
                          color: AppColors.describeColor, fontSize: 14))
                ],
              ),
            ),
          ),
          const SizedBox(
            width: 10,
          ),
          Container(
            padding: const EdgeInsets.only(right: 24),
            child: GestureDetector(
              onTap: () {
                _databaseService.updateMediaLike(
                    widget.media.videoId ?? 0, widget.media.like == 1 ? 0 : 1);
                setState(() {
                  widget.media.like = widget.media.like == 0 ? 1 : 0;
                });
              },
              child: Image.asset(
                widget.media.like == 1
                    ? 'images/icon_creation_like.png'
                    : 'images/icon_creation_unlike.png',
                width: 48,
                height: 48,
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    debugPrint('${Uri.parse(widget.media.mediaUrl!)}');
    videoPlayFuture = fetchController();
    widget.videoPlayerController.addListener(() {
      if(mounted){
        if(widget.videoPlayerController.value.isPlaying){
          setState(() {
            loading = false;
          });
        }
      }
    });
  }

  Future<void> fetchController() async{
    return widget.videoPlayerController.initialize().then((_) {
      if (mounted) {
        widget.videoPlayerController.setLooping(true);
        if(widget.pageIndex == 1 && !widget.videoPlayerController.value.isPlaying) {
          widget.videoPlayerController.play();
        }
      }
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void didUpdateWidget(covariant VideoPlayItemPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if(widget.media.videoId != oldWidget.media.videoId){
      oldWidget.videoPlayerController.dispose();
      debugPrint('==================================updatewidget');
      if(!widget.videoPlayerController.value.isInitialized){
          videoPlayFuture = widget.videoPlayerController.initialize().then((_) {
              widget.videoPlayerController.setLooping(true);
              if( widget.pageIndex == 1 && !widget.videoPlayerController.value.isPlaying) {
                widget.videoPlayerController.play();
                debugPrint('==================================update play');
              }
        });
      }else{
        if(!widget.videoPlayerController.value.isPlaying){
          widget.videoPlayerController.play();
        }
      }
    }
    setState(() {playing = true;});
  }

  @override
  Widget build(BuildContext context) {
    if(widget.videoPlayerController.value.isPlaying){
      playing = true;
      loading = false;
    }
    if(!widget.videoPlayerController.value.isPlaying && !widget.videoPlayerController.value.isInitialized){
      loading = true;
    }

    return FutureBuilder(
        future: videoPlayFuture,
        builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
            return Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: NetworkImage(widget.media.thumbUrl!),
                        fit: BoxFit.fill)),
                height: double.infinity,
                child:
                snapshot.connectionState == ConnectionState.done?
              AspectRatio(
                    aspectRatio: widget.videoPlayerController.value.aspectRatio,
                    child: Stack(children: [
                      widget.videoPlayerController.value.isInitialized
                          ? InkWell(
                        onTap: () {
                          if (widget
                              .videoPlayerController.value.isPlaying) {
                            widget.videoPlayerController.pause();
                            playing = false;
                          } else {
                            widget.videoPlayerController.play();
                            playing = true;
                          }
                          setState(() {});
                        },
                        child: Stack(
                          children: [
                            VideoPlayer(widget.videoPlayerController),
                            Visibility(
                                visible: !playing,
                                child: Center(
                                    child: Image.asset(
                                        'images/icon_pause.png',
                                        width: 60,
                                        height: 60))),
                            Visibility(
                                visible: loading,
                                child: const Center(
                                  child: CircularProgressIndicator(),
                                ))
                          ],
                        ),
                      )
                          : Container(
                        alignment: Alignment.center,
                        child: const CircularProgressIndicator(),
                      ),
                      Container(
                        padding: EdgeInsets.only(top: getDeviceTop(context)),
                        child: _appBarView,
                      ),
                      Positioned(bottom: 30, child: _bottomView(context)),
                    ])):const Center(child:CircularProgressIndicator())
            );
          }
        );
  }

  _showBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Visibility(
                    visible: !(author!.isFriend ?? false),
                    child: ListTile(
                        title: const Center(child: Text('Follow')),
                        onTap: () {
                          setState(() {
                            loading = true;
                          });
                          BroadCasterDao.addFriend(int.parse(author!.userId!),
                              () {
                            setState(() {
                              loading = false;
                            });
                            _databaseService.updateAuthorFriend(
                                int.parse(author!.userId!), true);
                            setState(() {
                              author!.isFriend = true;
                            });
                            appToast.showTipLong('Follow Successfully');
                            Navigator.pop(context);
                          });
                        })),
                ListTile(
                    title: const Center(
                      child: Text('Block'),
                    ),
                    onTap: () {
                      setState(() {
                        loading = true;
                      });
                      BroadCasterDao.block(int.parse(author!.userId!), () {
                        setState(() {
                          loading = false;
                        });
                        widget.onBlock();
                        // _databaseController.fetchCreationData();
                        // _databaseController.fetchMediaData();
                        appToast.showTipLong('Block Successfully');
                        Navigator.pop(context);
                      });
                    }),
                ListTile(
                    title: const Center(
                      child: Text('Report'),
                    ),
                    onTap: () {
                      Navigator.pop(context);
                      _showSecondBottomSheet();
                    }),
                ListTile(
                    title: const Center(
                      child: Text('Cancel'),
                    ),
                    onTap: () {
                      Navigator.pop(context);
                    }),
              ],
            ),
          );
        });
  }

  void _showSecondBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _reportItem('Pornographic'),
                _reportItem('False gender'),
                _reportItem('Fraud'),
                _reportItem('Political sensitive'),
                _reportItem('Other'),
                ListTile(
                    title: const Center(
                      child: Text('Cancel'),
                    ),
                    onTap: () {
                      Navigator.pop(context);
                    }),
              ],
            ),
          );
        });
  }

  Widget _reportItem(String complainSub) {
    return ListTile(
        title: Center(child: Text(complainSub)),
        onTap: () {
          setState(() {
            loading = true;
          });
          BroadCasterDao.report(int.parse(author!.userId!), complainSub, () {
            setState(() {
              loading = false;
            });
            Navigator.pop(context);
            appToast.showTipLong('Report Successfully');
          });
        });
  }
}
